<template>
  <div>

    <!-- 如无需展开查询，请移除:advanced.sync="advanced"并添加:no-advanced="true" -->
    <e-pro-table title="文章管理" :advanced.sync="advanced">
      <template slot="query">
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-model-item label="标题">
            <a-input v-model="queryParam.title"/>
          </a-form-model-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-model-item label="栏目">
            <cascader
              :options="columnTree"
              placeholder="请选择栏目"
              :show-search="{ columnFilter }"
              v-model="columnId"
              @change="setColumn"/>
          </a-form-model-item>
        </a-col>
        <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
          <a-form-model-item label="状态">
            <e-dict-select v-model="queryParam.status" type="cmsArticleStatus" @change="$refs.eTable.refresh(true)"/>
          </a-form-model-item>
        </a-col>
        <template v-if="advanced">
          <!-- 点击展开显示的查询条件 -->
          <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
            <a-form-model-item label="作者">
              <a-input v-model="queryParam.author"/>
            </a-form-model-item>
          </a-col>
        </template>
      </template>

      <template slot="button">
        <e-btn-add
          :permissions="CMS_ARTICLE_CONST.CMS_ARTICLE_SAVE"
          :to="`/cms/article/input?columnId=${queryParam.columnId ? queryParam.columnId : ''}`"/>
        <e-btn-remove-batch
          :permissions="CMS_ARTICLE_CONST.CMS_ARTICLE_REMOVE"
          :loading.sync="removeBathLoading"
          :ids="selectedRowKeys"
          :click-callback="remove"/>
      </template>

      <template slot="table">
        <s-table
          ref="eTable"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowSelection="rowSelection"
          showPagination="auto"
        >
          <template #coverPath="text">
            <div class="cover-preview">
              <img v-if="text" :src="VUE_APP_API_BASE_URL + text">
            </div>
          </template>

          <template #status="text">
            <e-dict-tag type="cmsArticleStatus" :code="text"/>
          </template>

          <template #action="text, record">
            <a-tooltip placement="top">
              <template #title>
                <span>预览</span>
              </template>
              <a-button size="small" icon="eye" @click="preview(record)"/>
            </a-tooltip>
            <a-divider type="vertical"/>

            <e-btn-edit
              permissions="cms:article:save"
              :to="`/cms/article/input`"
              :tab-name="record.title"
              :id="record.id"/>

            <a-tooltip placement="top">
              <template #title>
                <span>发布</span>
              </template>
              <a-button type="primary" size="small" icon="check" @click="release(record.id)"/>
            </a-tooltip>

            <template v-if="record.status === CMS_ARTICLE_CONST.PUBLISHED">
              <a-divider type="vertical"/>
              <a-tooltip placement="top">
                <template #title>
                  <span>撤销</span>
                </template>
                <a-button size="small" icon="rollback" @click="revoke(record.id)"/>
              </a-tooltip>
            </template>
            <a-divider type="vertical"/>
            <e-btn-remove
              :permissions="CMS_ARTICLE_CONST.CMS_ARTICLE_REMOVE"
              :id="record.id"
              :divider="false"
              :click-callback="remove"/>

          </template>
        </s-table>
      </template>
    </e-pro-table>
    <cms-chose-site @change="changeSite"/>
  </div>
</template>

<script>
import { Cascader } from 'ant-design-vue'
import { select, remove, release, revoke } from '@/api/cms/article'
import { convertTree, formatDate } from '@/utils/util'
import { STable, Ellipsis } from '@/components'
import EProTable from '@/components/Easy/data-display/ProTable'
import EBtnAdd from '@/components/Easy/general/BtnAdd'
import EBtnEdit from '@/components/Easy/general/BtnEdit'
import EBtnRemove from '@/components/Easy/general/BtnRemove'
import EBtnRemoveBatch from '@/components/Easy/general/BtnRemoveBatch'
import EDictTag from '@/components/Easy/data-display/DictTag'
import EDictSelect from '@/components/Easy/data-entry/DictSelect'
import CmsChoseSite from '@/views/cms/ChoseSite'
import { selectColumnsByUserId } from '@/api/cms/column/user'
import { CMS_ARTICLE_CONST } from '@/utils/const/cms/CmsArticleConst'

const columns = [
  {
    title: '封面',
    dataIndex: 'coverPath',
    width: 120,
    scopedSlots: { customRender: 'coverPath' }
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 260,
    sorter: true
  },
  {
    title: '栏目',
    dataIndex: 'columnName',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 80,
    sorter: true,
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '发布时间',
    dataIndex: 'releaseDate',
    width: 150,
    sorter: true,
    customRender: (text) => formatDate(text)
  },
  // {
  //   title: '下线时间',
  //   dataIndex: 'offlineDate',
  //   width: 150,
  //   sorter: true,
  //   customRender: (text) => formatDate(text)
  // },
  {
    title: '作者',
    dataIndex: 'author',
    width: 80,
    sorter: true
  },
  // {
  //   title: '浏览次数',
  //   dataIndex: 'viewCount',
  //   width: 100,
  //   sorter: true
  // },
  {
    title: '更新人',
    dataIndex: 'editUser',
    width: 80,
    sorter: true
  },
  {
    title: '更新时间',
    dataIndex: 'editDate',
    width: 170,
    sorter: true,
    customRender: (text) => formatDate(text)
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 220,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'CmsArticleList',
  components: {
    CmsChoseSite,
    STable,
    Ellipsis,
    EProTable,
    EBtnAdd,
    EBtnEdit,
    EBtnRemove,
    EBtnRemoveBatch,
    EDictTag,
    EDictSelect,
    Cascader
  },
  data () {
    this.columns = columns
    return {
      VUE_APP_API_BASE_URL: process.env.VUE_APP_API_BASE_URL,
      CMS_ARTICLE_CONST: CMS_ARTICLE_CONST,
      // 查询参数
      advanced: false,
      queryParam: {},
      // 栏目数据
      column: [],
      columnTree: [],
      columnId: [],

      selectedRowKeys: [],
      selectedRows: [],
      removeBathLoading: false,
      releaseBtnLoading: false,
      revokeBtnLoading: false
    }
  },
  mounted () {
    this.loadColumns()
  },
  activated () {
    this.$refs.eTable.refresh(true)
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    changeSite () {
      this.$refs.eTable.refresh(true)
    },
    // 加载数据方法 必须为 Promise 对象
    loadData (parameter) {
      const requestParameters = Object.assign({}, parameter, this.queryParam)
      return select(requestParameters)
        .then(res => {
          return res.data
        })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    loadColumns () {
      selectColumnsByUserId().then(({ data }) => {
        this.column = data
        this.convertCascaderData()
      })
    },
    convertCascaderData () {
      function convert (tempColumnTree) {
        const node = []
        for (let i = 0; i < tempColumnTree.length; i += 1) {
          if (tempColumnTree[i].children && tempColumnTree[i].children.length) {
            node.push({
              value: tempColumnTree[i].id,
              label: tempColumnTree[i].name,
              children: convert(tempColumnTree[i].children)
            })
          } else {
            node.push({
              value: tempColumnTree[i].id,
              label: tempColumnTree[i].name
            })
          }
        }
        return node
      }

      this.columnTree = convert(convertTree(this.column, '0'))
    },
    columnFilter (inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },
    setColumn (value) {
      if (value.length) {
        this.queryParam.columnId = value[value.length - 1]
      } else {
        this.queryParam.columnId = null
      }
      this.$refs.eTable.refresh(true)
    },
    remove (id) {
      remove(id).then(res => {
        this.$refs.eTable.refresh()
        this.removeBathLoading = false
      }).catch(({ response }) => {
        this.removeBathLoading = false
      })
    },
    release (id) {
      release(id).then(res => {
        this.$refs.eTable.refresh()
        this.$message.success(`发布成功`)
      })
    },
    revoke (id) {
      revoke(id).then(res => {
        this.$refs.eTable.refresh()
        this.$message.success(`撤销成功`)
      })
    },
    preview (record) {
      window.open(`${this.VUE_APP_API_BASE_URL}/cms/route/${record.siteId}/article/${record.id}`)
    }
  }
}
</script>
<style lang="less" scoped>
.cover-preview {
  height: 44px;
  margin: -6px 0;
  position: relative;

  img {
    max-width: 100%;
    max-height: 100%;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>
